/**
 * ------------------------------------------------------
 *  学生信息列表页
 * ------------------------------------------------------
 *
 * Note: .
 *
 */
import { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { Card, Breadcrumb, Form, Button, Input, Select, Popconfirm,message,Table, Tag, Space } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { useClasses } from '@/hooks/useClasses'
import { delStudentAPI, getStudentListAPI } from '@/apis/student'
import { PAGE_SIZE } from '@/config/constants'

const { Option } = Select

const Student = () => {
  const navigate = useNavigate()
  const [messageApi,contextHolder] = message.useMessage();
  const {classesList} = useClasses()
  //定义性别枚举
  const gender = {
    0 : <Tag color='warning'>女</Tag>,
    1 : <Tag color='success'>男</Tag>
  }
  //定义表格列
  const columns = [
    {
      title: '学号',
      dataIndex: 'studentid',
      width: 120
    },
    {
      title: '姓名',
      dataIndex: 'fullname',
      width: 120
    },
    {
      title: '性别',
      dataIndex: 'gender',
      width: 50,
      render: data => gender[data]
    },
    {
      title: '班级',
      dataIndex: 'classes_name'
    },
    {
      title: '手机号',
      dataIndex: 'mobile'
    },        
    {
      title: '操作',
      width: 160,
      render: data => {
        return (
          <Space size="middle">
            <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={()=>navigate(`/student/publish?id=${data.id}`)} />
            <Popconfirm
              title="删除"
              placement="left"
              description="确认要删除当前学生信息吗?"
              onConfirm={() => onConfirm(data)}
              okText="删除"
              cancelText="取消"
            >
              <Button
                type="primary"
                danger
                shape="circle"
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        )
      }
    }
  ]
    
  //筛选参数（含分页）
  const [reqData,setReqData] = useState({
    gender:'',
    classesid:'',
    page:1,
    per_page:PAGE_SIZE
  })

  //获取学生信息列表
  const [list,setList] = useState([])
  const [count,setCount] = useState(0)
  useEffect(()=>{
    async function getList(){
      const res = await getStudentListAPI(reqData)
      setList(res.data.results)   
      setCount(res.data.total_rows)     
    }
    getList()
  },[reqData])

  //获取筛选数据（搜索表单）
  const onFinish = (formValue) =>{
    //更新筛选参数
    setReqData({
      ...reqData,
      classesid:formValue.classesid,
      gender:formValue.gender,
      keyword:formValue.keyword
    })
  }

  //分页
  const onPageChange =(page)=>{
    //修改参数依赖项 引发数据重新获取列表渲染
    setReqData({
      ...reqData,
      page
    })
  }
    
  //删除确认
  const onConfirm = async (data) =>{
    await delStudentAPI(data.id)
    setReqData({
      ...reqData
    })
    messageApi.success('删除成功',1)
  }

  return (
    <div>
      <Card
        title={
          <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> },
            { title: '学生列表' },
          ]} />
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{ classesid: '', gender: '' }} layout="inline" onFinish={onFinish}>
          
          <Form.Item label="班级" name="classesid">
            <Select placeholder="全部" style={{ width: 120 }}
            >
              <Select.Option value={''}>全部</Select.Option>
              {classesList.map(item => <Option key={item.id} value={item.id}>{item.title}</Option>)}
            </Select>
          </Form.Item>

          <Form.Item label="性别" name="gender">
            <Select placeholder="全部" style={{ width: 70 }}>
              <Select.Option value={''}>全部</Select.Option>
              <Select.Option value={1}>男</Select.Option>
              <Select.Option value={0}>女</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item label="关键字" name="keyword">
            <Input placeholder="姓名/学号/手机号" style={{ width: 220 }} />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginLeft: 40 }}>
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      {/* 表格区域 */}
      <Card title={`根据筛选条件共查询到 ${count} 条结果：`}>
        <Table rowKey="id" columns={columns} dataSource={list} pagination={{
          total:count,
          pageSize:reqData.per_page,
          showSizeChanger:false,
          onChange:onPageChange,
        }} />
      </Card>
      {contextHolder}
    </div>
  )
}

export default Student